package linkedlist;

/**
 * 给你单链表的头指针 head 和两个整数 left 和 right ，其中 left <= right 。
 * 请你反转从位置 left 到位置 right 的链表节点，返回 反转后的链表 。
 */
public class no92 {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(head == null || head.next == null || left == right){
            return head;
        }
        ListNode cur = head;
        ListNode slow = head;
        ListNode fast = head;

        int left_ = left;
        while (left-1 > 0){
            slow = slow.next;
            left--;
        }
        while (left_-2 > 0){
            cur = cur.next;
            left_--;
        }
        while (right-1 > 0){
            fast = fast.next;
            right--;
        }
        if(cur == slow){
            head = fast;
        }else{
            cur.next = fast;
        }

        ListNode prev = slow.next;
        slow.next = fast.next;

        while (slow != fast){
            ListNode next = slow;
            slow = prev;
            prev = prev.next;
            slow.next = next;
        }
        return head;
    }
}
